package meng.dubbo.demo.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import meng.dubbo.demo.model.Student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("studentDao")
public class StudentDao {

	@Autowired
	private NamedParameterJdbcTemplate jdbcTemplate;

	public void add(Student stu) {
		String sql = "INSERT INTO student (stuName,phase) VALUES (:stuName,:phase)";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("stuName", stu.getStuName());
		paramMap.put("phase", stu.getPhase());
		jdbcTemplate.update(sql, paramMap);
	}

	public void update(Student stu) {
		StringBuilder sql = new StringBuilder();
		sql.append(" update student set stuName=:stuName where stuId=:stuId ");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("stuName", stu.getStuName());
		jdbcTemplate.update(sql.toString(), paramMap);
	}

	public void delete(int id) {
		String sql = "delete from student where stuId=:stuId ";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		jdbcTemplate.update(sql, paramMap);
	}

	public Student getById(int id) {
		String sql = "SELECT stuId,stuName,phase from student where stuId = "+id;
		List<Student> list = jdbcTemplate.query(sql,
				new BeanPropertyRowMapper<Student>(Student.class));
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public List<Student> getAll() {
		String sql = "SELECT stuId,stuName,phase from student ";
		List<Student> list = jdbcTemplate.query(sql,
				new BeanPropertyRowMapper<Student>(Student.class));
		return list;
	}
}
